package cn.xspace.wnx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BBizList;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.been.CommonItemBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.IntentConstant;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;
import com.xspace.android.xafcommon.view.dialog.DialogHelp;
import com.xspace.android.xafcommon.view.dialog.PopupWindowHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.entity.ServiceObjBean;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ServiceObjDetailActivity extends BaseActivity {

    public static final String TAG = ServiceObjDetailActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private TextView object_typename;
    private TextView user_name;
    private TextView user_mobile;
    private TextView factory_name;
    private TextView feed_type;
    private TextView shengtai;
    private TextView countryQu;
    private TextView townsZhen;
    private TextView villagesCun;
    private TextView agencyShe;
    private TextView longitude;
    private TextView latitude;
    private TextView nj_username;
    private ListView listView;

    private ServiceObjBean mServiceObjBean;

    private String user_id;
    private String serviceobj_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void getIntentData() {
        user_id = MyInfoUtil.getMyUserid(mContext);
        serviceobj_id = getIntent().getStringExtra(IntentConstant.serviceobj_id);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_service_obj_detail);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.service_object_title_bar);
        object_typename = (TextView) findViewById(R.id.tv_service_obj_type);
        user_name = (TextView) findViewById(R.id.txt_charge_name);
        user_mobile = (TextView) findViewById(R.id.txt_charge_phone);
        factory_name = (TextView) findViewById(R.id.txt_org_name);
        feed_type = (TextView) findViewById(R.id.txt_feed_type);
        shengtai = (TextView) findViewById(R.id.tv_service_sheng_tai);
        countryQu = (TextView) findViewById(R.id.txt_area_country);
        townsZhen = (TextView) findViewById(R.id.txt_in_towns);
        villagesCun = (TextView) findViewById(R.id.txt_in_villages);
        agencyShe = (TextView) findViewById(R.id.txt_in_agency);
        longitude = (TextView) findViewById(R.id.txt_detail_longitude);
        latitude = (TextView) findViewById(R.id.txt_detail_latitude);
        nj_username = (TextView) findViewById(R.id.txt_g_work_item_nj);
        listView = (ListView) findViewById(R.id.lv_service_detail);
    }

    @Override
    protected void initData() {
        requestNetWorkData();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMorePopup(mTitleBar.getRightImage());
            }
        });
    }

    private void requestNetWorkData() {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("serviceobj_id", serviceobj_id);
        registerSubscription(OkHttpManager.getInstance().commonRequest(Constants.QUERY_SERVICE_OBJ_DETAIL, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, ServiceObjBean>() {
                    @Override
                    public ServiceObjBean call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<ServiceObjBean>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<ServiceObjBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ServiceObjBean serviceObjBean) {
                        hideWaitDialog();
                        if (serviceObjBean == null) {
                            T.show(mContext, getResources().getString(R.string.request_data_error), Toast.LENGTH_SHORT);
                            return;
                        }
                        mServiceObjBean = serviceObjBean;
                        setData(serviceObjBean);
                    }
                }));
    }


    private void setData(ServiceObjBean serviceObjBean) {
        object_typename.setText(serviceObjBean.object_typename);

        user_name.setText(serviceObjBean.user_name);
        user_mobile.setText(serviceObjBean.user_mobile);
        factory_name.setText(serviceObjBean.factory_name);
        feed_type.setText(serviceObjBean.breed_codename);
        //生态养殖
        if (!TextUtils.isEmpty(serviceObjBean.shengtai_flag)) {
            if ("0".equals(serviceObjBean.shengtai_flag)) {
                shengtai.setText(R.string.text_no);
            } else if ("1".equals(serviceObjBean.shengtai_flag)) {
                shengtai.setText(R.string.text_yes);
            }
        }
        countryQu.setText(serviceObjBean.user_quname);
        townsZhen.setText(serviceObjBean.user_zhenname);
        agencyShe.setText(serviceObjBean.user_shename);
        villagesCun.setText(serviceObjBean.user_cunname);
        latitude.setText(serviceObjBean.latitude);
        longitude.setText(serviceObjBean.longitude);

        nj_username.setText(serviceObjBean.nj_username);
        fillView(serviceObjBean.bizList);
        object_typename.setFocusable(true);
        object_typename.setFocusableInTouchMode(true);
        object_typename.requestFocus();
    }

    private void fillView(final List<BBizList> list) {
        listView.setAdapter(new ArrayAdapter<BBizList>(mContext, R.layout.animal_use_item, list) {
            @NonNull
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                BBizList item = list.get(position);
                if (convertView == null) {
                    convertView = View.inflate(mContext, R.layout.animal_use_item, null);
                }
                TextView animalName = (TextView) convertView.findViewById(R.id.animal_name);
                TextView animalUse = (TextView) convertView.findViewById(R.id.animal_use);
                TextView animalCount = (TextView) convertView.findViewById(R.id.animal_count);
                animalName.setText(checkNull(item.biz_name));
                animalUse.setText(checkNull(item.animal_use_name));
                animalCount.setText(checkNull(item.animal_count));
                return convertView;
            }
        });
    }

    private String checkNull(String string) {
        if (TextUtils.isEmpty(string) || string.contains("null")) {
            return "";
        } else {
            return string;
        }
    }

    private void showMorePopup(View v) {
        PopupWindowHelper helper = PopupWindowHelper.newInstance(mContext);
        ArrayList<CommonItemBean> list = new ArrayList<>();
        list.add(new CommonItemBean(getString(R.string.edit), 1));
        list.add(new CommonItemBean(getString(R.string.stop), 2));
        helper.setDataList(list)
                .setListener(new PopupWindowHelper.IPopupClickListener() {
                    @Override
                    public void onItemClick(View view, CommonItemBean bean, int position) {
                        switch (bean.tag) {
                            case 1://编辑
                                Intent intent = new Intent(mContext, ServiceObjModifyActivity.class);
                                intent.putExtra(IntentConstant.isEditInfo, true);
                                intent.putExtra(IntentConstant.serviceObjBean, mServiceObjBean);
                                startActivity(intent);
                                break;
                            case 2://停用
                                showStopDialog();
                                break;
                        }
                    }
                }).showPopup(v);
    }

    private void showStopDialog() {
        DialogHelp.getConfirmDialogWithoutContent(mContext, getString(R.string.stop_service_object),
                getString(R.string.think_again_and_again),
                getString(R.string.button_ok), null, new ButtonClickListener() {
                    @Override
                    public void buttonClick(View view) {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("user_id", user_id);
                        map.put("serviceobj_id", serviceobj_id);
                        OkHttpManager.getInstance().commonRequest(Constants.STOP_SERVICE_OBJ, map)
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Subscriber<BaseReturnBean>() {
                                    @Override
                                    public void onCompleted() {
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        hideWaitDialog();
                                        e.printStackTrace();
                                        T.showSingleL(e.getMessage());
                                    }

                                    @Override
                                    public void onNext(BaseReturnBean baseReturnBean) {
                                        hideWaitDialog();
                                        T.showSingleL(baseReturnBean.desc);
                                        HashMap<String, Object> eventMap = new HashMap<>();
                                        eventMap.put(EventBusConstant.TYPE, EventBusConstant
                                                .SERVICE_OBJECT_STOP_SUCCESS);
                                        eventMap.put(EventBusConstant.ACTION_KEY, serviceobj_id);
                                        EventBus.getDefault().post(eventMap);
                                        finish();
                                    }
                                });
                    }
                }).show();
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        String type = inParam.get(EventBusConstant.TYPE).toString();
        if (EventBusConstant.SERVICE_OBJECT_EDIT_SUCCESS.equals(type)) {
            mServiceObjBean = (ServiceObjBean) inParam.get(EventBusConstant.ACTION_VALUE);
            setData(mServiceObjBean);
//            requestNetWorkData();
        }
    }
}
